'''
Created on 2014-4-24

@author: ASUS
'''
import matplotlib.pyplot as plt
from fetch_info_to_file.Review_Stuff import Review_Stuff
from numpy.random.mtrand import np
from fetch_info_to_file.fetch_price_trend import Get_price_trend
from fetch_info_to_file.ASIN import get_ASIN
from read_list_from_file.read_price_list import Get_Price_List
from matplotlib.dates import DateFormatter, rrulewrapper, RRuleLocator,YEARLY,\
    drange
from datetime import datetime

class draw_stars(object):
    asins=[]
    asin_price_average={}
    def draw_histogram(self, axi_x, axi_y, x_label, title):
        y_pos = np.arange(len(axi_y))
        performance = axi_x
        error = 0
        plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4)
        plt.yticks(y_pos, axi_y)
        plt.xlabel(x_label)
        plt.title(title)
        plt.show()

    def draw_overall_pie(self, sizes,title):
        labels = '0 star', '0-1 star', '1-2 stars', '2-3 stars', '3-4 stars', '4-5 stars'
        colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', 'grey', 'red']
        explode = (0.1, 0.2, 0, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

        plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
        plt.axis('equal')
        plt.title(title)
        plt.show()
    
    def get_avg_rank(self, l):
        zero = 0
        zero_one = 0
        one_two = 0
        two_three = 0
        three_four = 0
        four_five = 0
        for single in l:
            if single['avg_rank'] == 0:
                zero = zero + 1
            elif 0.0 < float(single['avg_rank']) <= 1.0:
                zero_one = zero_one + 1
            elif 1.0 < float(single['avg_rank']) <= 2.0:
                one_two = one_two + 1
            elif 2.0 < float(single['avg_rank']) <= 3.0:
                two_three = two_three + 1
            elif 3.0 < float(single['avg_rank']) <= 4.0:
                three_four = three_four + 1
            elif 4.0 < float(single['avg_rank']) <= 5.0:
                four_five = four_five + 1
        count_list = [zero, zero_one, one_two, two_three, three_four, four_five]
        print count_list
        return count_list
    
    def get_avg_rank_y(self):
        y_list = ['0', '0-1', '1-2', '2-3', '3-4', '4-5']
        return y_list
    
    def get_pie_sizes(self,l):
        stars = self.get_avg_rank(l)
        size = []
        total = 0.0
        for number in stars:
            total = total + number
        for star in stars:
            size.append((float(star / total)) * 100)
        return size
    
    def get_several_level_ranks(self,level_range,fileName):
        high_level_number = self.seperate_levels(level_range,fileName)['high']
        middle_level_number=self.seperate_levels(level_range,fileName)['middle']
        low_level_number=self.seperate_levels(level_range,fileName)['low']
        high_stars=[]
        middle_stars=[]
        low_stars=[]
        for i in high_level_number:
            high_star={'avg_rank':i['avg_rank']}
            high_stars.append(high_star)
        for i in middle_level_number:
            middle_star={'avg_rank':i['avg_rank']}
            middle_stars.append(middle_star)
        for i in low_level_number:
            low_star={'avg_rank':i['avg_rank']}
            low_stars.append(low_star)
        several_star_rank={'high':high_stars,'middle':middle_stars,'low':low_stars}
        return several_star_rank
    
    def seperate_levels(self,level_range,fileName):
        g = Get_Price_List()
        asin = Review_Stuff()
        asin_prices = g.get_infolist()
        high = []
        middle = []
        low = []
        asin_review_count_ranks = asin.get_review_counts_average_rank(fileName)
        asins_in_price=[]
        for single in asin_prices:
            asins_in_price.append(single['ASIN'])
        for asin_review_count_rank in asin_review_count_ranks:
            ASIN=asin_review_count_rank['ASIN']+'\n'
            temp_price=0.0
            count=asins_in_price.count(ASIN)/2
            print count
            if count!=0:
                for i in range(0,count+1):
                    number=asins_in_price.index(ASIN)+i
                    temp_price=temp_price+asin_prices[number]['price']
                p=temp_price/count
            else:
                p=0.0
            asin_price_review_rank = {'ASIN':ASIN, 'price':p,
                                               'review_count':asin_review_count_rank['review_count'], 
                                               'avg_rank':asin_review_count_rank['avg_rank']}
            if 0<=p<=int(level_range['low']):
                        low.append(asin_price_review_rank)
            elif int(level_range['low'])<p<=int(level_range['middle']):
                        middle.append(asin_price_review_rank)
            elif p>int(level_range['middle']):
                        high.append(asin_price_review_rank)
               
        level = {'high':high, 'middle':middle, 'low':low}
        return level    

    def seperate_time(self,time_str):
        year_month_day=time_str.split(' ')[0]
        hour_minute_second=time_str.split(' ')[1]
        time={'year':year_month_day.split('-')[0],'month':year_month_day.split('-')[1],
              'day':year_month_day.split('-')[2],'hour':hour_minute_second.split(':')[0],
              'minute':hour_minute_second.split(':')[1]}
        return time
    
    def combine_asin_time_avg_rank(self,asin_input):
        g = Get_Price_List()
       
        
        asin_prices_time = g.get_infolist()
        
        asins_in_price=[]
        for single in asin_prices_time:
            asins_in_price.append(single['ASIN'])
        
        
        temp_ASIN=asin_input+'\n'
        count=asins_in_price.count(temp_ASIN)/2
            
        price_time_avgranks=[]
        if count!=0:
            for i in range(0,count+1):
                number=asins_in_price.index(temp_ASIN)+i
                temp_price=asin_prices_time[number]['price']
                temp_time=self.seperate_time(asin_prices_time[number]['time'])
                avg_rank=self.get_temp_avg_rank(asin_input,temp_time)
                price__time_avgrank={'price':temp_price,'time':temp_time,'avg_rank':avg_rank}
                price_time_avgranks.append(price__time_avgrank)
        else:
            temp_price=0.0
            temp_time=''
            price__time_avgrank={'price':temp_price,'time':temp_time,'avg_rank':0.0}  
            price_time_avgranks.append(price__time_avgrank)     
        asin_time_avg_rank={'ASIN':asin_input,'time_avg_rank':price_time_avgranks}
        self.asin_price_average=asin_time_avg_rank 
        
        print self.asin_price_average
        return asin_time_avg_rank
    
    def get_temp_avg_rank(self,ASIN,end_time):
        number=self.asins.index(ASIN)
        R=Review_Stuff()
        overall_list=R.readFromLocal('Review_Stuff')
        reviews=overall_list[number]['single_review']
        count=0
        stars=0
        for single_review in reviews:
            temp_time=self.seperate_time(single_review['time'])
            if self.compare_time(temp_time, end_time)==-1:
                if len(single_review['rank'])!=0:
                    stars=stars+float((single_review['rank'].split(' ')[0]))
                    count=count+1
        if count!=0:
            temp_avg_rank=float(stars)/count
        else:
            temp_avg_rank=0
        return temp_avg_rank
    
    def compare_time(self,time_1,time_2):
        if int(time_1['year'])>int(time_2['year']):
            return 1
        elif int(time_1['year'])<int(time_2['year']):
            return -1
        elif int(time_1['year'])==int(time_2['year']):
            if int(time_1['month'])>int(time_2['month']):
                return 1
            elif int(time_1['month'])<int(time_2['month']):
                return -1
            elif int(time_1['month'])==int(time_2['month']):
                if int(time_1['day'])>int(time_2['day']):
                    return 1
                elif int(time_1['day'])<int(time_2['day']):
                    return -1
                elif int(time_1['day'])==int(time_2['day']):
                    if int(time_1['hour'])>int(time_2['hour']):
                        return 1
                    elif int(time_1['hour'])<int(time_2['hour']):
                        return -1
                    elif int(time_1['hour'])==int(time_2['hour']):
                        if int(time_1['minute'])>int(time_2['minute']):
                            return 1
                        elif int(time_1['minute'])<int(time_2['minute']):
                            return -1
                        elif int(time_1['minute'])==int(time_2['minute']):
                            return 0
    def getASIN(self,category):
        R=Review_Stuff()
        R.setCategory(category)
        l=R.readFromLocal('woman_jeans_review')
        for single in l:
            self.asins.append(single['ASIN'])
    
    def draw_several_histogram(self):
        return 
    
    def draw_product_price_rank_line(self,ASIN_Number):
        price_list=[]
        avg_rank_list=[]
        self.combine_asin_time_avg_rank(ASIN_Number)
        for single in self.asin_price_average['time_avg_rank']:
            price_list.append(single['price'])
            avg_rank_list.append(single['avg_rank'])
        ASIN=self.asin_price_average['ASIN']
        plt.plot(price_list, avg_rank_list, 'o--')
        plt.xlabel('price')
        plt.ylabel('average_rank')
        plt.title('Changes of average rank by the change of '+ASIN+'\'s price')
        plt.show()
     
    def draw_time_rank(self,x,y,ASIN):
        ax = plt.subplots()
        dates=[]
        formatter = DateFormatter('%Y-%m-%d %H:%M:%S')
        for date in x:
            dates.append(datetime.strptime(date,'%Y-%m-%d %H:%M:%S'))
        area = np.pi * (2)**2 # 0 to 15 point radiuses
        plt.scatter(dates,y, s=area, alpha=0.5)
        plt.xlabel('date of review')
        plt.ylabel('stars')
        plt.title(ASIN)
        plt.show()
       
       
       

    def get_times(self,ASIN,file_name):
        times=[]
        number=self.asins.index(ASIN)
        
        R=Review_Stuff()
        overall_list=R.readFromLocal(file_name)
        single=overall_list[number]       
        for s in single['single_review']:
            times.append(s['time'])
        return times
    
    def get_ranks_within_time(self,ASIN,file_name):
        number=self.asins.index(ASIN)
        R=Review_Stuff()
        overall_list=R.readFromLocal(file_name)
        single=overall_list[number]
        singles=single['single_review']
        l=[]
        for s in singles:
            l.append(int(s['rank'].split(' ')[0].split('.')[0]))
        return l 
   
    
if __name__ == '__main__':
     d=draw_stars()
     d.getASIN('Clothing $ Accessories>Women>Jeans')
     
     #d.draw_time_rank(d.get_times('B00C9HE3QE','woman_jeans_review'),d.get_ranks_within_time('B00C9HE3QE', 'woman_jeans_review'),'B00C9HE3QE')
     level_range={'middle':370,'low':250}
     d.draw_histogram(d.get_avg_rank(d.get_several_level_ranks(level_range,'woman_jeans_review')['high']), d.get_avg_rank_y(), 'count', 'average stars of high level of cell phone')
     d.draw_histogram(d.get_avg_rank(d.get_several_level_ranks(level_range,'woman_jeans_review')['middle']), d.get_avg_rank_y(), 'count', 'average stars of middle level of cell phone')
     d.draw_histogram(d.get_avg_rank(d.get_several_level_ranks(level_range,'woman_jeans_review')['low']), d.get_avg_rank_y(), 'count', 'average stars of low level of cell phone')
     d.draw_overall_pie(d.get_pie_sizes(d.get_several_level_ranks(level_range,'woman_jeans_review')['low']),'pie of average star rank of low-level-price cell phone')
     d.draw_overall_pie(d.get_pie_sizes(d.get_several_level_ranks(level_range,'woman_jeans_review')['middle']),'pie of average star rank of middle-level-price cell phone')
     d.draw_overall_pie(d.get_pie_sizes(d.get_several_level_ranks(level_range,'woman_jeans_review')['high']),'pie of average star rank of high-level-price cell phone')
     
     
     #d.combine_asin_time_avg_rank('')
     #d.draw_product_price_rank_line('B00EKT26AE')
     #d.draw_product_price_rank_line('B00F2SGBXK')
     #d.draw_product_price_rank_line('B00D3OK4RO')
    # d.draw_product_price_rank_line('B00C6OYZRM') 
     #d.draw_product_price_rank_line('B00ENONLEQ')
     #d.draw_product_price_rank_line('B00CFXWTKO')
     #d.draw_product_price_rank_line('B00EP2CLII')
   # d.draw_product_price_rank_line('B00EKXDL0E')
    #print d.get_avg_rank(d.seperate_levels()['high'])
    #d.draw_histogram(d.get_avg_rank(d.seperate_levels()['high']),d.get_avg_rank_y(),'stars', 'high')
    